import axios from 'axios'

class fetchInstance {
    instance
    interceptors

    constructor(config) {
        this.instance = axios.create(config)
        this.interceptors = config.interceptors

        this.instance.interceptors.request.use(
            this.interceptors?.requestInterceptor,
            this.interceptors?.requestInterceptorCatch
        )

        this.instance.interceptors.response.use(
            this.interceptors?.responseInterceptor,
            this.interceptors?.responseInterceptorCatch
        )

        this.instance.interceptors.request.use(
            (config) => {
                return config
            },
            (err) => {
                return err
            }
        )
        this.instance.interceptors.response.use(
            (res) => {
                return res
            },
            (err) => {
                return err
            }
        )
    }
    request(config) {
        return new Promise((resolve, reject) => {
            if (config.interceptors?.requestInterceptor) {
                config = config.interceptors.requestInterceptor(config)
            }

            this.instance
                .request(config)
                .then((res) => {
                    if (config.interceptors?.responseInterceptor) {
                        res = config.interceptors.responseInterceptor(res)
                    }
                    resolve(res)
                })
                .catch((err) => {
                    reject(err)
                    return err
                })
        })
    }

    // get请求
    get(config) {
        return this.request({ ...config, method: 'GET' })
    }
    // post请求
    post(config) {
        return this.request({ ...config, method: 'POST' })
    }
    // delete请求
    delete(config) {
        return this.request({ ...config, method: 'DELETE' })
    }
    // patch请求
    patch(config) {
        return this.request({ ...config, method: 'PATCH' })
    }
    // put请求
    put(config) {
        return this.request({ ...config, method: 'PUT' })
    }
}

export default fetchInstance
